package cn.qianxun.meta.dept.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.hutool.core.convert.Convert;
import cn.qianxun.meta.common.core.dto.RowsData;
import cn.qianxun.meta.common.core.utils.StringUtils;
import cn.qianxun.meta.common.core.web.dto.SelectLongDTO;
import cn.qianxun.meta.common.core.web.dto.SelectStringDTO;
import cn.qianxun.meta.common.core.web.dto.SelectVO;
import cn.qianxun.meta.common.log.annotation.Log;
import cn.qianxun.meta.common.log.enums.BusinessType;
import cn.qianxun.meta.dept.dto.SysDeptAddDTO;
import cn.qianxun.meta.dept.dto.SysDeptQueryDTO;
import cn.qianxun.meta.dept.dto.SysDeptStatusDTO;
import cn.qianxun.meta.dept.vo.SysDeptVO;
import cn.qianxun.meta.user.dto.UserDeptRoleSelectDTO;
import cn.qianxun.meta.common.core.constant.UserConstants;
import cn.qianxun.meta.common.core.domain.Result;
import cn.qianxun.meta.common.security.resdata.SelectPageDTO;
import cn.qianxun.meta.dept.service.ISysDeptService;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * <p>
 * 部门表 前端控制器
 * </p>
 *
 * @author fuzhilin
 * @since 2023-08-21 02:30:54
 */
@Tag(name = "组织机构管理")
@Validated
@RestController
@RequiredArgsConstructor(onConstructor_ = @Autowired)
@RequestMapping("/web/v1/sysDept")
public class SysDeptController {

    private final ISysDeptService sysDeptService;

    /**
     * 获取部门列表
     */
    @SaCheckPermission("web:v1:dept:list")
    @PostMapping("/list")
    public Result<List<SysDeptVO>> list(@RequestBody SysDeptQueryDTO dto) {
        return Result.success("查询成功", sysDeptService.selectDeptList(dto));
    }

    /**
     * 查询部门列表（排除节点）
     *
     * @param selectLongDTO 部门ID
     */
    @SaCheckPermission("web:v1:dept:list")
    @PostMapping("/list/exclude")
    public Result<List<SysDeptVO>> excludeChild(@RequestBody SelectLongDTO selectLongDTO) {
        List<SysDeptVO> depts = sysDeptService.excludeChild(selectLongDTO);
        depts.removeIf(d -> d.getDeptId().intValue() == selectLongDTO.getIdLong() || StringUtils.splitList(d.getAncestors()).contains(Convert.toStr(selectLongDTO.getIdLong())));
        return Result.success(depts);
    }

    /**
     * 根据部门编号获取详细信息
     *
     * @param selectLongDTO 部门ID
     */
    @SaCheckPermission("web:v1:dept:getDeptById")
    @PostMapping(value = "/getDeptById")
    public Result<SysDeptVO> getDeptById(@RequestBody SelectLongDTO selectLongDTO) {
        sysDeptService.checkDeptDataScope(selectLongDTO.getIdLong());
        return Result.success(sysDeptService.selectDeptById(selectLongDTO.getIdLong()));
    }

    /**
     * 新增部门
     */
    @SaCheckPermission("web:v1:dept:add")
    @Log(title = "部门管理", businessType = BusinessType.INSERT)
    @PostMapping(value = "/addDept")
    public Result<Object> add(@Validated @RequestBody SysDeptAddDTO sysDeptAddDTO) {
        if (!sysDeptService.checkDeptNameUnique(sysDeptAddDTO)) {
            return Result.fail("新增部门'" + sysDeptAddDTO.getDeptName() + "'失败，部门名称已存在");
        }
        sysDeptService.insertDept(sysDeptAddDTO);
        return Result.success("操作成功");
    }

    /**
     * 修改部门
     */
    @SaCheckPermission("web:v1:dept:edit")
    //@ChangeLog(moduleName = "组织机构", serviceclass = ISysDeptService.class, idType = Long.class, idName = "deptId")
    @Log(title = "部门管理", businessType = BusinessType.UPDATE)
    @PostMapping(value = "/editDept")
    public Result<Object> edit(@Validated @RequestBody SysDeptAddDTO dept) {
        Long deptId = dept.getDeptId();
        if (StringUtils.isNull(dept.getParentId())) {
            dept.setParentId(0L);
        }
        sysDeptService.checkDeptDataScope(deptId);
        if (!sysDeptService.checkDeptNameUnique(dept)) {
            return Result.fail("修改部门'" + dept.getDeptName() + "'失败，部门名称已存在");
        } else if (dept.getParentId().equals(deptId)) {
            return Result.fail("修改部门'" + dept.getDeptName() + "'失败，上级部门不能是自己");
        } else if (StringUtils.equals(UserConstants.DEPT_DISABLE, dept.getStatus()) && sysDeptService.selectNormalChildrenDeptById(deptId) > 0) {
            return Result.fail("该部门包含未停用的子部门！");
        }
        return Result.success(sysDeptService.updateDept(dept));
    }

    /**
     * 删除部门
     */
    @SaCheckPermission("web:v1:dept:remove")
    @Log(title = "部门管理", businessType = BusinessType.DELETE)
    @PostMapping(value = "/delDeptById")
    public Result<Object> delDeptById(@RequestBody SelectLongDTO selectLongDTO) {
        if (sysDeptService.hasChildByDeptId(selectLongDTO.getIdLong())) {
            return Result.fail("存在下级部门,不允许删除");
        }
        if (sysDeptService.checkDeptExistUser(selectLongDTO.getIdLong())) {
            return Result.fail("部门存在用户,不允许删除");
        }
        sysDeptService.checkDeptDataScope(selectLongDTO.getIdLong());
        sysDeptService.deleteDeptById(selectLongDTO.getIdLong());
        return Result.success("操作成功");
    }

    /**
     * 修改单位状态
     *
     * @param dto
     * @return
     */
    @SaCheckPermission("web:v1:dept:status")
    @PostMapping(value = "/status")
    public Result<String> status(@RequestBody SysDeptStatusDTO dto) {
        sysDeptService.status(dto);
        return Result.success("修改成功");
    }

    /**
     * 责任单位下拉选
     *
     * @param dto
     * @return
     */
    @PostMapping(value = "/deptList")
    public Result<RowsData<SelectVO>> getDeptList(@RequestBody SelectPageDTO dto) {
        return Result.success("查询成功", sysDeptService.getDeptList(dto));
    }

    /**
     * 运维单位下拉选
     *
     * @param dto
     * @return
     */
    @PostMapping(value = "/operateSubList")
    public Result<RowsData<SelectVO>> operateSubList(@RequestBody SelectPageDTO dto) {
        return Result.success("查询成功", sysDeptService.operateSubList(dto));
    }

    /**
     * 使用单位下拉选
     *
     * @param dto
     * @return
     */
    @PostMapping(value = "/useSubList")
    public Result<RowsData<SelectVO>> useSubList(@RequestBody SelectPageDTO dto) {
        return Result.success("查询成功", sysDeptService.useSubList(dto));
    }

    /**
     * 根据单位id获取单位负责人的电话和姓名
     *
     * @param dto
     * @return
     */
    @PostMapping(value = "/getDeptLeaderInfo")
    public Result<SelectVO> getDeptLeaderInfo(@RequestBody SelectStringDTO dto) {
        return Result.success("查询成功", sysDeptService.getDeptLeaderInfo(dto));
    }

    /**
     * 流程 单位下拉选(不分页)
     *
     * @param dto dto
     * @return List<SelectVO>
     */
    @SaCheckPermission("web:v1:dept:getProcessDeptList")
    @PostMapping("/getProcessDeptList")
    public Result<List<SelectVO>> getProcessDeptList(@RequestBody UserDeptRoleSelectDTO dto) {
        return Result.success("查询成功", sysDeptService.getProcessDeptList(dto));
    }

    /**
     * 流程 单位下拉选(分页)
     *
     * @param dto dto
     * @return RowsData<SelectVO>
     */
    @SaCheckPermission("web:v1:dept:getProcessDeptPageList")
    @PostMapping("/getProcessDeptPageList")
    public Result<RowsData<SelectVO>> getProcessDeptPageList(@RequestBody UserDeptRoleSelectDTO dto) {
        return Result.success("查询成功", sysDeptService.getProcessDeptPageList(dto));
    }

}
